# -*- coding: utf-8 -*-
"""
@desc: 登录管理模块
"""
from flask import Blueprint, request, jsonify, render_template
from flask_login import login_user, login_required, current_user, logout_user
from models import User
import json
import hashlib

user = Blueprint('user', __name__)

@user.route('/user/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        json_data = json.loads(request.get_data().decode('utf-8'))
        username = json_data.get('username')
        password = json_data.get('password')
        print('user_name: %s ; password: %s' % (username, password))
        # 去数据库查询是否存在
        user_ = User.query.filter_by(username=username).first()
        if user_ and user_.password == password and user_.is_active == 'Y': # 登录成功
            print('用户%s密码验证成功' % username)
            login_user(user_)
            print('用户%s登录成功' % username)
            return jsonify({"status_code":200, 'info':"登录成功"})
        else:
            return json.dumps({"status_code":401, "reason":"用户名或密码错误"}, ensure_ascii=False)
    elif request.method == 'GET':
        return json.dumps({"status_code":200, "info":"请使用post方法"}, ensure_ascii=False)

@user.route('/user/info')
@login_required
def index():
    result = {'id':current_user.id,
              'name': current_user.name,
              'username': current_user.username,
              'department':current_user.department,
              'email': current_user.email,
              'officePhone': current_user.office_telephone,
              'role':current_user.role_id}
    return jsonify(result)

@user.route('/user/logout', methods=['GET', 'POST'])
@login_required
def logout():
    logout_user()
    return jsonify({"status_code":200, 'info':'success'})